package com.learn.sunday.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.learn.sunday.auth.bean.DigestBean;
import com.learn.sunday.auth.bean.User;
import com.learn.sunday.auth.dao.UserDao;
import com.learn.sunday.auth.service.UserService;
import com.learn.sunday.common.service.ResponseUtil;
import com.learn.sunday.common.service.utils.DigestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Value("${digest.user.realm:user_realm}")
    private String userRealm;

    @Value("${digest.user.key:user_xxxxxxxxxxxx}")
    private String userKey;


    @Value("${digest.user.valid.time:180}")
    private Integer validTime;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = new User();
        user.setUsername(s);
        return userDao.selectOne(user);
    }



    @Override
    public void login(HttpServletRequest request, HttpServletResponse response) {
        final String authorization = request.getHeader("authorization");
        if (StringUtils.isBlank(authorization)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            String authHeader = DigestUtils.generateAuthHeader(validTime, userRealm, userKey);
            log.info("第一次登录生成的鉴权响应头是:{}",authHeader);
            response.addHeader("Authenticate", authHeader);
        } else {

            DigestBean digestBean = new DigestBean(authorization);
            boolean b = digestBean.validateAndDecode(userKey, userRealm);
            if (!b) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED,"认证信息错误! ");
                return;
            }
            String username = digestBean.getUsername();
            redisTemplate.opsForValue().set(username,username,300000L);
            log.info("二次认证信息:{}", JSON.toJSONString(digestBean));
        }
    }

    @Override
    public ResponseUtil getUserList() {
        List<User> users = userDao.selectAll();
        return ResponseUtil.success().data(users);
    }
}
